package cn.ffcs.util.converter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import ognl.DefaultTypeConverter;
import ognl.ParseException;

public class DateConverter extends DefaultTypeConverter 
{
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");  
    
    public Object convertValue(Map ognlContext, Object value, Class toType) {           
        Object result = null;  
        if (toType == Date.class) {  
            result = doConvertToDate(value);  
        } else if (toType == String.class) {  
           result = doConvertToString(value);  
       }  
       return result;  
   }  
 
   private Date doConvertToDate(Object value) {  
       Date result = null;  
 
       if (value instanceof String) {  
           try {  
               result = sdf.parse((String) value);  
           } catch (Exception e) {  
               //e.printStackTrace(); 
            System.out.println("dateconverter is failed!");
           }  
       } else if (value instanceof Object[]) {  
           // let's try to convert the first element only  
           Object[] array = (Object[]) value;  
           if ((array != null) && (array.length >= 1)) {  
              value = array[0];  
               result = doConvertToDate(value);  
           }  
       } else if (Date.class.isAssignableFrom(value.getClass())) {  
           result = (Date) value;  
       }  
       return result;  
   }  
 
   private String doConvertToString(Object value) {  
       String result = null;  
       if (value instanceof Date) {  
           result = sdf.format(value);  
       }  
       return result;  
   }  
   
   /**
    * 日期加减
    */
   public static Date computeDate(Date date,int num){
       Calendar calendar=Calendar.getInstance();   
       calendar.setTime(date);
       System.out.println(calendar.getTime());
       calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+num);//让日期加num
//       System.out.println(calendar.getTime());
       return calendar.getTime();
   }

}
